package com.ylkj.wx.facade.impl;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.xml.sax.InputSource;

import com.ylkj.wx.constant.WeiXBaseConstant;
import com.ylkj.wx.dto.ValidateFormDto;
import com.ylkj.wx.facade.EntranceMessageFacade;
import com.ylkj.wx.message.resp.Article;
import com.ylkj.wx.message.resp.BaseMessage;
import com.ylkj.wx.message.resp.NewsMessage;
import com.ylkj.wx.message.resp.TextMessage;
import com.ylkj.wx.utils.MessageUtil;
import com.ylkj.wx.utils.SignUtil;



@Service("entranceMessageFacade")
public class EntranceMessageFacadeImpl implements EntranceMessageFacade {
    private static final Logger LOGGER = LoggerFactory.getLogger(EntranceMessageFacadeImpl.class);
    
    /**
     * 微信请求校验，确认请求来自微信服务器
     * @param form
     * @param value
     * @param out
     */
	public void firstEntranceHandel(ValidateFormDto form, String value, PrintWriter out){
        String token = WeiXBaseConstant.WEIXIN_TOKEN;
		// 微信加密签名
		String signature = form.getSignature();
		// 时间戳
		String timestamp = form.getTimestamp();
		// 随机数
		String nonce = form.getNonce();
		// 随机字符串
		String echostr = form.getEchostr();
		
        LOGGER.info("token:"+token);
        LOGGER.info("signature :"+signature);
        LOGGER.info("timestamp :"+timestamp);
        LOGGER.info("nonce :"+nonce);
		try{
			// 请求校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
			if (SignUtil.checkSignature(token, signature, timestamp, nonce)) {
				out.print(echostr);
	            out.flush();
	            out.close();
	            LOGGER.info("接入成功！");
			}
		}catch(Exception e){
            LOGGER.error("接入失败,sha1:! signature:" + signature,e.getMessage(),e);
		}
	}
    
 
    /**
     * 处理用户发给微信平台的消息
     * @param form
     * @param value
     * @param out
     */
	public void messageEntranceHandel(ValidateFormDto form, String value, PrintWriter out){
        String token = WeiXBaseConstant.WEIXIN_TOKEN;
        LOGGER.info("token:"+token);
		// 微信加密签名
		String signature = form.getSignature();
		// 时间戳
		String timestamp = form.getTimestamp();
        LOGGER.info("timestamp :"+timestamp);
		// 随机数
		String nonce = form.getNonce();

        LOGGER.info("nonce :"+nonce);
		try{
			// 请求校验，防止恶意访问
			if (SignUtil.checkSignature(token, signature, timestamp, nonce)) {
				messageEntranceByEvent(value,out);
	           
	            LOGGER.info("响应成功！");
			}
		}catch(Exception e){
            LOGGER.error("响应失败,sha1:! signature:" + signature,e.getMessage(),e);
		}
	}
	
    /**
     * 处理用户发给微信平台的消息
     * @param value
     * @param out
     * @param response
     * @throws Exception 
     */
	private void messageEntranceByEvent(String value, PrintWriter out) throws Exception{

		try{
			long startTime = System.currentTimeMillis();
			LOGGER.info("响应开始时间："+startTime);
            StringReader xmlReader = new StringReader(value);
            /**
             * 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入 
             */
            InputSource xmlSource = new InputSource(xmlReader);
            /** 
             * 创建一个SAXBuilder 
             */
            SAXBuilder builder = new SAXBuilder();
            /** 
             * 通过输入源SAX构造一个Document 
             */
            org.jdom.Document doc = builder.build(xmlSource);
            Element element = doc.getRootElement();
            String strToUserName = "";//开发者微信号
            String strFromUserName = ""; // 发送方OpenId
            String strMsgType = ""; //消息类型（目前只支持text）

            Element toUserName = element.getChild("ToUserName");
            if(toUserName != null){
            	strToUserName = toUserName.getText();
	            LOGGER.info("开发者微信号:" + strToUserName);
            }
            
            Element fromUserName = element.getChild("FromUserName");
            if(fromUserName != null){
            	strFromUserName = fromUserName.getText();
	            LOGGER.info("发送方OpenId:" + strFromUserName);
            }
            
            Element createTime = element.getChild("CreateTime");
            LOGGER.info("消息创建时间:" + createTime.getText());

            Element msgType = element.getChild("MsgType");
			if (msgType != null) {
				strMsgType = msgType.getText();
				LOGGER.info("消息类型:" + strMsgType);
				BaseMessage baseMessage = new BaseMessage();
				//开发者微信号
				baseMessage.setFromUserName(strToUserName);
				//接收方帐号（收到的OpenID）
				baseMessage.setToUserName(strFromUserName);
				
				//1 如果是文本消息类型
				if (WeiXBaseConstant.REQ_MESSAGE_TYPE_TEXT.equals(strMsgType)) {
					Element content = element.getChild("Content");
					if (content != null) {
						String strContent = content.getText();
						LOGGER.info("发送方1content:" + strContent);
						//根据扫描或输入的doectorCloudCode后的响应
						String ct = welcomeResponseText(baseMessage);
						LOGGER.info("=====:" + ct);
//						String ct1 = new String(ct.getBytes(),"UTF-8");
						LOGGER.info("=====:" + ct);
						out.print(ct);
						
						
//						String str = "<?xml encoding=utf-8><ToUserName><![CDATA[oFrLyvhV9qZiW9Oglsd6T6Uymzr4]]>"
//								+ "</ToUserName><FromUserName><![CDATA[gh_37c5f5e8cba2]]>"
//								+ "</FromUserName><CreateTime><![CDATA[1474798294355]]>"
//								+ "</CreateTime><MsgType><![CDATA[text]]></MsgType>"
//								+ "<Content><![CDATA[您好]]></Content></xml>";
						//out.println("您好");
					}
					
				} 
				//2  请求消息类型为事件推送(扫码，自定义菜单点击等)的场合
				else if (WeiXBaseConstant.REQ_MESSAGE_TYPE_EVENT.equals(strMsgType)) {
					Element event = element.getChild("Event");
					if (event != null) {
						String strEvent = event.getText();
						LOGGER.info("事件类型:" + strEvent);
						String strEvnetKey = "";
						Element eventKey = element.getChild("EventKey");
						if (eventKey != null) {
							strEvnetKey = eventKey.getText();
							LOGGER.info("事件KEY:" + strEvnetKey);
						}
						
						//2.1 事件类型为扫码(已经关注，带参数？)的场合
						if(WeiXBaseConstant.EVENT_TYPE_SCAN.equals(strEvent)){
							/*if(StringUtils.isNotBlank(strEvnetKey)){
								//获得参数中的云医生号
								String doctorCloudCode = strEvnetKey;
									//根据扫描或输入的doctorCloudCode后的响应
									makeDoctorCloudCodeResponse(doctorCloudCode, out, baseMessage);
							}else{*/
								//设置没有参数的二维码的响应
								//makeWelcomeMessage(strEvent, out, baseMessage);
						    String ct = welcomeResponse(baseMessage);
	                        out.print(ct);
							
						}
						
						//2.2 事件类型为订阅/关注的场合
						else if (WeiXBaseConstant.EVENT_TYPE_SUBSCRIBE.equals(strEvent)) {
						   /* String ct = welcomeResponse(baseMessage);
                            out.print(ct);
							if(StringUtils.isNotBlank(strEvnetKey)){
								// TODO 二维码中参数在EvnetKey的qrscene_前缀之后
								if(strEvnetKey.startsWith(WeiXBaseConstant.EVENT_KEY_QRSCENE)){
									//获得参数中的云医生号
										//根据扫描或输入的doctorCloudCode后的响应
										//makeDoctorCloudCodeResponse(doctorCloudCode, out, baseMessage);
									
								//对应IOS的关注事件是带参数的特殊处理
								}else{
									makeWelcomeMessage(strEvent, out, baseMessage);
								}
							}else{
								//设置没有参数的二维码的响应
								makeWelcomeMessage(strEvent, out, baseMessage);
							}*/
							String ct = welcomeResponseAttention(baseMessage);
							out.print(ct);
							
						} 
						//2.3 事件类型为自定义菜单的场合
						else if (WeiXBaseConstant.EVENT_TYPE_CLICK.equals(strEvent)) {
							//自定义菜单点击【我的医生】的场合
							if(WeiXBaseConstant.MY_DOCTOR.equals(strEvnetKey)){
								//点击自定菜单【我的医生】的响应 
								makeMyDoctorResponse(out, baseMessage);
								
								//自定义菜单点击【我的服务】的场合
							}
//							else if(WeiXBaseConstant.MY_SERVICE.equals(strEvnetKey)){
								//TODO 暂时挪到url里来实现
								//makeMyServiceResponse(out, baseMessage);
//							}
							
						}
						//2.4 获得地理位置的场合
						else if(WeiXBaseConstant.EVENT_TYPE_LOCATION.equals(strEvent)){
				            Element latitude = element.getChild("Latitude");
				            if(latitude != null){
				            	String strLatitude = latitude.getText();
								LOGGER.info("当前用户的地理位置纬度是" + strLatitude);
				            }
				            
				            Element longitude = element.getChild("Longitude");
				            if(latitude != null){
				            	String strLongitude = longitude.getText();
								LOGGER.info("当前用户的地理位置经度是" + strLongitude);
				            }
				            
				            Element precision = element.getChild("Precision");
				            if(latitude != null){
				            	String strPrecision = precision.getText();
								LOGGER.info("当前用户的地理位置精度是" + strPrecision);
				            }
						}
					}
				}
				
				
				//3  请求消息类型为语音的场合
				else if(WeiXBaseConstant.REQ_MESSAGE_TYPE_VOICE.equals(strMsgType)){
					//设置请求消息为音频的的响应
					makeVoiceResponse(out, baseMessage);
				}
				
				
				//4 请求消息类型为视频的场合
				else if(WeiXBaseConstant.REQ_MESSAGE_TYPE_VIDEO.equals(strMsgType)){
					//设置请求消息为视频的的响应
					makeVedioResponse(out, baseMessage);
				}
				
				//5  请求消息类型为小视频的场合
				else if(WeiXBaseConstant.EVENT_TYPE_SHORTVIDEO.equals(strMsgType)){
					//设置请求消息为小视频的的响应
					makeShortVedioResponse(out, baseMessage);
				}
				
				//6 请求消息类型为图片的场合
				else if(WeiXBaseConstant.REQ_MESSAGE_TYPE_IMAGE.equals(strMsgType)){
		            Element mediaId = element.getChild("MediaId");
					String strMediaId = "";
		            if(mediaId != null){
		            	strMediaId = mediaId.getText();
		            }
					//设置请求消息为图片的的响应
					//makeImageResponse(out, baseMessage, strMediaId);
				}
			}
			long endTime = System.currentTimeMillis();
			LOGGER.info("响应结束时间："+endTime);
			LOGGER.info("总共耗时："+(endTime-startTime));
        }catch (JDOMException e) {
            LOGGER.error("用户消息解析失败!",e.getMessage(),e);
        }catch (IOException e) {
            LOGGER.error("用户消息解析失败!",e.getMessage(),e);
        }
	}
	
	
	//设置点击自定菜单【我的医生】的响应
	private void makeMyDoctorResponse(PrintWriter out, BaseMessage baseMessage)
			throws IllegalAccessException, InvocationTargetException
			 {
		String strResponse = "";
		// 根据openid获得用户的phrCode
		String personCode = findPersonCodeByOpenId(baseMessage.getToUserName());
		// 首先判断是否完善个人信息
		strResponse = setPersonInfoResponse(baseMessage, personCode, "",
				baseMessage.getToUserName());
			
//					strResponse = sendMessageToWhichDoctorResponse(baseMessage,
//							"", lstDoctorInfoDto, personCode);
		out.write(strResponse);
	}
	
	//设置请求消息为音频的的响应
	private void makeVoiceResponse(PrintWriter out, BaseMessage baseMessage)
			throws IllegalAccessException, InvocationTargetException {
	 // 对不起，目前尚不支持发送视屏信息。
        String strResponse = noSupportServiceResponse(
                baseMessage,
                "对不起，目前尚不支持音频发送");
        out.write(strResponse);
	}
	
	//设置请求消息为视频的的响应
	private void makeVedioResponse(PrintWriter out, BaseMessage baseMessage)
			throws IllegalAccessException, InvocationTargetException {
		// 对不起，目前尚不支持发送视屏信息。
		String strResponse = noSupportServiceResponse(
				baseMessage,
				"对不起，目前尚不支持视频发送");
		out.write(strResponse);
	}
	
	// 设置请求消息为小视频的的响应
	private void makeShortVedioResponse(PrintWriter out, BaseMessage baseMessage)
			throws IllegalAccessException, InvocationTargetException {
		TextMessage textMessage = new TextMessage();
		copyBaseMessageToSubMessage(textMessage, baseMessage);
		textMessage.setContent("对不起，目前尚不支持小视频发送");
		textMessage.setCreateTime(System.currentTimeMillis());
		textMessage.setMsgType(WeiXBaseConstant.RESP_MESSAGE_TYPE_TEXT);
		String strResponse = MessageUtil.messageToXml(textMessage);
		out.write(strResponse);
	}
	
	
	
	
	//设置输入文本类型的响应
	/*private void makeInputTextResponse(String content, PrintWriter out,
			BaseMessage baseMessage) throws Exception {
		String strResponse = ""; // 响应信息
		if (doectorCloudCode == null) {
			// 扫描或输入的云医生号错误时，公众号的回应
			strResponse = errorDoctorCodeResponse(baseMessage);
		} else {
					// 回复医生名片内容
					strResponse = doctorCardResponse(baseMessage, "personCode",
							"doctorCode", "doctorName");
				}
		out.write(strResponse);
	}*/
	
	//验证接受的文本是否是指定长度的数字
	private boolean checkIsDoctorCloudCode(String value){
		boolean flag = false;
		//判断长度 
		if(StringUtils.isNotBlank(value) 
				&& value.length() == WeiXBaseConstant.DOCTOR_ID_LENGTH){
		    Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");    
		    flag = pattern.matcher(value).matches(); 
		}
		
		return flag;
	}
	
	//将父类的属性拷贝到子类
	private void copyBaseMessageToSubMessage(Object subMessage, Object baseMessage){
		try {
			//基础内容copy
			BeanUtils.copyProperties(subMessage, baseMessage);
		} catch (IllegalAccessException e) {
            LOGGER.error("类型转换失败!",e.getMessage(),e);
		} catch (InvocationTargetException e) {
            LOGGER.error("类型转换失败!",e.getMessage(),e);
		}
	}
	
	// 设置没有参数的二维码的响应
	private void makeWelcomeMessage(String strEvent, PrintWriter out,
			BaseMessage baseMessage) throws Exception
		 {
		// 回复医生不存在的内容
		String strResponse = "";
		String personCode = "";
		// TODO 设置回复文本内容
		// 扫描带参数的二维码的场合
		if (WeiXBaseConstant.EVENT_TYPE_SCAN.equals(strEvent)) {
			//二维码有问题的响应
			strResponse = errorQRCodeResponse(baseMessage);
			// 关注的场合
		} else if (WeiXBaseConstant.EVENT_TYPE_SUBSCRIBE.equals(strEvent)) {
			// 根据openid获得用户的phrCode,用来判断该用户是否以前曾经关注过.
			 personCode = findPersonCodeByOpenId(baseMessage
					.getToUserName());
			// 关注过的场合
			if (StringUtils.isNotBlank(personCode)) {
				//再次关注并且已经存在个人信息的用户的响应
				strResponse = welcomeResponse(baseMessage);				
				// 没有关注的场合
			} else {
				//根据openid获得用户的phrCode
				personCode = findPersonCodeByOpenId(baseMessage.getToUserName());
				LOGGER.info("personCode is"+personCode);
				//如果personCode为空，则是通过医生名片首次关注
				if(StringUtils.isBlank(personCode)){
					//在微信用户信息中新增一条记录
					saveMemberInfo(baseMessage.getToUserName());
				}
				//	//只关注了服务号（没有医生）的响应
				strResponse = welcomeResponse(baseMessage);
			}
		}
		out.write(strResponse);
	}
	
	// 根据openid获得用户的phrCode
	private String findPersonCodeByOpenId(String openId) {
        String personCode = "";
        return personCode;
	}
	

	
	// 当扫描或输入的doectorCloudCode后的添加医生与用户的临时关注关系
	private void savePatientAttentionTemp(String doctorCode, String openId)
			throws Exception {
	}
	
	// 当扫描或输入的doectorCloudCode后的添加医生与用户的关注关系
	private void savePatientAttention(String doctorCode, String personCode) throws Exception {
	}
	
	//判断是否完善了个人信息，如果没有完善，则提示一个图文消息。
	private String setPersonInfoResponse(BaseMessage baseMessage,
			String personCode, String doctorName, String openId)
			 {
		String strResponse = "";
		return strResponse;
	}
	
	//在微信用户信息中新增一条记录
	private void saveMemberInfo(String openId) throws Exception {
			// 在微信用户信息中新增一条记录
	}


		
	
	
//	// 再次关注公众号的用户，公众号的回应
//	private String attentionAgainResponse(TextMessage textMessage) {
//		// 提示欢迎回来
//		textMessage.setContent(MessageBundleReader.getBundle().getString(
//				"WELCOME_VISIT"));
//		textMessage.setCreateTime(System.currentTimeMillis());
//		textMessage.setMsgType(WeiXBaseConstant.RESP_MESSAGE_TYPE_TEXT);
//		String strResponse = MessageUtil.messageToXml(textMessage);
//		return strResponse;
//	}
	
	// ok 公众号的回应: 扫描或输入的云医生号错误时，
	private String errorDoctorCodeResponse(BaseMessage baseMessage){
		// 回复医生不存在的内容
		TextMessage textMessage = new TextMessage();
		copyBaseMessageToSubMessage(textMessage, baseMessage);
		// TODO 设置回复文本内容
		// 医生不存在，请确认医生的“云医号”！
		textMessage.setContent("医生不存在，请确认医生的“云医号”！");
		textMessage.setCreateTime(System.currentTimeMillis());
		textMessage.setMsgType(WeiXBaseConstant.RESP_MESSAGE_TYPE_TEXT);
		String strResponse = MessageUtil.messageToXml(textMessage);
		return strResponse;
	}
	
	//OK 公众号的回应:图文列表；扫码或输入云医生号时，
	private String doctorCardResponse(BaseMessage baseMessage,
			String personCode, String doctorCode, String doctorName) {
		// 回复医生名片内容
		NewsMessage newsMessage = new NewsMessage();
		// TODO 根据doctorInfo设置医生名片的相关信息
		// 拷贝基本属性到图文
		copyBaseMessageToSubMessage(newsMessage, baseMessage);
		newsMessage.setMsgType(WeiXBaseConstant.RESP_MESSAGE_TYPE_NEWS);
		// 设置图文消息个数
		newsMessage.setArticleCount(2);
		List<Article> lstArticle = new ArrayList<Article>();
		Article mainArticle = new Article();
		String strMainTitle = String.format("您已关注%s医生，打个招呼吧！", doctorName);
		mainArticle.setTitle(strMainTitle);

		// 进入IM的图片
		mainArticle.setPicUrl(WeiXBaseConstant.WEIXIN_DOMAIN_URL + "/wx/res/images/doctor_attention.png");
		// 拼接IM主页链接
		String imUrl = WeiXBaseConstant.WEIXIN_DOMAIN_URL
				+ "/wx/page/index/#/consult?doctorCode=" + doctorCode
				+ "&personCode=" + personCode;
		mainArticle.setUrl(imUrl);
		lstArticle.add(mainArticle);
		
		Article subArticle = new Article();
		subArticle.setTitle("熙心医生----随时随地联系你的医生");
		subArticle.setDescription("了解更多主页");
		// 图片&链接
		subArticle.setPicUrl(WeiXBaseConstant.WEIXIN_DOMAIN_URL + "/wx/res/images/doctor_80_80.png");
		subArticle.setUrl(WeiXBaseConstant.WEIXIN_DOMAIN_URL + "/wx/page/presentation");
		lstArticle.add(subArticle);

		newsMessage.setArticles(lstArticle);

		String strResponse = MessageUtil.messageToXml(newsMessage);
		return strResponse;
	}
	
	//点击我的医生，只关注一名医生的场合，公众号的回应
	private String doctorServiceResponse(BaseMessage baseMessage,
			String personCode, String doctorCode, String doctorName) {
		TextMessage textMessage = new TextMessage();
		copyBaseMessageToSubMessage(textMessage, baseMessage);
		StringBuffer sb = new StringBuffer();
		// TODO 提示该医生提供的服务信息
		// 我的医生：{姓名}医生
		String strMessage = "我的医生：{姓名}医生";
		strMessage = String.format(strMessage, doctorName);
		sb.append(strMessage);
		sb.append("\n\r");

		// 我要咨询
		String imUrl = WeiXBaseConstant.WEIXIN_DOMAIN_URL
				+ "/wx/page/index/#/consult?doctorCode=" + doctorCode
				+ "&personCode=" + personCode;
		sb.append("<a href=\""
				+ imUrl
				+ "\">我要咨询</a>");
		sb.append("\n\r\n\r");

		// 医生主页
		String doctorUrl = WeiXBaseConstant.WEIXIN_DOMAIN_URL
				+ "/wx/page/index/#/doctor?doctorCode=" + doctorCode
				+ "&personCode=" + personCode;
		sb.append("<a href=\""
				+ doctorUrl
				+ "\"> 医生主页</a>");
		sb.append("\n\r\n\r");

		// 诊疗记录
		String prescriptionUrl = WeiXBaseConstant.WEIXIN_DOMAIN_URL
				+ "/wx/page/index/#/prescription?doctorCode=" + doctorCode
				+ "&personCode=" + personCode;
		LOGGER.info(prescriptionUrl);
		sb.append("<a href=\""
				+ prescriptionUrl
				+ "\"> 诊疗记录</a>");
		sb.append("\n\r\n\r");

		// 我的订单
		String orderUrl = WeiXBaseConstant.WEIXIN_DOMAIN_URL
				+ "/wx/page/index/#/order?personCode=" + personCode
				+ "&doctorCode=" + doctorCode;
		sb.append("<a href=\"" + orderUrl + "\"> "
				+ "我的订单"
				+ "</a>");

		textMessage.setContent(sb.toString());
		textMessage.setCreateTime(System.currentTimeMillis());
		textMessage.setMsgType(WeiXBaseConstant.RESP_MESSAGE_TYPE_TEXT);
		String strResponse = MessageUtil.messageToXml(textMessage);
		LOGGER.info(strResponse);
		return strResponse;
	}

	//没有关注医生的场合，公众号的回应
	private String noDoctorResponse(BaseMessage baseMessage) {
		TextMessage textMessage = new TextMessage();
		copyBaseMessageToSubMessage(textMessage, baseMessage);
		StringBuffer sb = new StringBuffer();
		// TODO 查询医生主页对应链接
		// 您还没有关注过医生？/r/n扫描医生的二维码名片或者输入医生的“云医号”快速关注医生！
		sb.append("您还没有关注过医生？");
		sb.append("\n\r");
		sb.append("扫描医生的二维码名片或者输入医生的“云医号”快速关注医生！");
		sb.append("\n\r\n\r");
		// 了解详情，请点这里！
		sb.append("<a href='"+WeiXBaseConstant.WEIXIN_DOMAIN_URL+"/wx/page/presentation'>了解详情，请点这里</a>");

		textMessage.setContent(sb.toString());
		textMessage.setCreateTime(System.currentTimeMillis());
		textMessage.setMsgType(WeiXBaseConstant.RESP_MESSAGE_TYPE_TEXT);
		String strResponse = MessageUtil.messageToXml(textMessage);
		return strResponse;
	}
	
	// 服务暂时未开通的场合，公众号的回应
	private String noSupportServiceResponse(BaseMessage baseMessage,
			String content) {
		TextMessage textMessage = new TextMessage();
		copyBaseMessageToSubMessage(textMessage, baseMessage);
		// 消息内容
		textMessage.setContent(content);
		textMessage.setCreateTime(System.currentTimeMillis());
		textMessage.setMsgType(WeiXBaseConstant.RESP_MESSAGE_TYPE_TEXT);
		String strResponse = MessageUtil.messageToXml(textMessage);
		return strResponse;
	}
	
	
	
	//OK 只关注了服务号（没有医生）或者再次关注并且已经存在个人信息的用户的响应
	private String welcomeResponse(BaseMessage baseMessage){
		List<Article> lstArticle = new ArrayList<Article>();
		// 返回首次访问的图文信息
		NewsMessage newsMessage = new NewsMessage();
		// 拷贝基本属性到图文
		copyBaseMessageToSubMessage(newsMessage, baseMessage);
		newsMessage.setMsgType(WeiXBaseConstant.RESP_MESSAGE_TYPE_NEWS);
		// 设置图文消息个数
		newsMessage.setArticleCount(1);

		Article mainArticle = new Article();
		mainArticle.setTitle("关注熙心健康，随时随地联系你的医生！");

		// 欢迎访问%s云医院主页
		StringBuffer sbMainDescription = new StringBuffer();
		sbMainDescription.append("\n\r");
		//1、关注医生云医号
		sbMainDescription.append("1、关注医生云医号");
		sbMainDescription.append("\n\r");
		sbMainDescription.append("2、通过微信随时随地咨询你的医生");
		sbMainDescription.append("\n\r");
		sbMainDescription.append("3、在线购药，配送到家");
		sbMainDescription.append("\n\r");
		sbMainDescription.append("详细信息请点击查看");

		mainArticle.setDescription(sbMainDescription.toString());
		// TODO 图片&链接
		mainArticle.setPicUrl(WeiXBaseConstant.WEIXIN_DOMAIN_URL + "/wx/res/images/welcome.png");
		mainArticle.setUrl(WeiXBaseConstant.WEIXIN_DOMAIN_URL + "/wx/page/presentation");
		lstArticle.add(mainArticle);
		
		newsMessage.setArticles(lstArticle);

		String strResponse = MessageUtil.messageToXml(newsMessage);
		return strResponse;
	}
	
	
	private String welcomeResponseText(BaseMessage baseMessage){
		TextMessage textMessage = new TextMessage();
		copyBaseMessageToSubMessage(textMessage, baseMessage);
		// 您扫描的二维码有问题，请询问医生重新获得二维码。
		textMessage.setContent("1、有问题请与与本站客服联系，联系电话：024-XXXXXX");
		textMessage.setCreateTime(System.currentTimeMillis());
		textMessage.setMsgType(WeiXBaseConstant.RESP_MESSAGE_TYPE_TEXT);
		String strResponse = MessageUtil.messageToXml(textMessage);
		return strResponse;
	}
	
	private String welcomeResponseAttention(BaseMessage baseMessage){
		TextMessage textMessage = new TextMessage();
		copyBaseMessageToSubMessage(textMessage, baseMessage);
		// 您扫描的二维码有问题，请询问医生重新获得二维码。
		textMessage.setContent("欢迎进入好合友平台，本站将竭诚为您服务！");
		textMessage.setCreateTime(System.currentTimeMillis());
		textMessage.setMsgType(WeiXBaseConstant.RESP_MESSAGE_TYPE_TEXT);
		String strResponse = MessageUtil.messageToXml(textMessage);
		return strResponse;
		
	}
	
	//二维码有问题的响应
	private String errorQRCodeResponse(BaseMessage baseMessage){
		TextMessage textMessage = new TextMessage();
		copyBaseMessageToSubMessage(textMessage, baseMessage);
		// 您扫描的二维码有问题，请询问医生重新获得二维码。
		textMessage.setContent(" 您扫描的二维码有问题，请询问要打赏的服务人员，重新获得二维码");
		textMessage.setCreateTime(System.currentTimeMillis());
		textMessage.setMsgType(WeiXBaseConstant.RESP_MESSAGE_TYPE_TEXT);
		String strResponse = MessageUtil.messageToXml(textMessage);
		return strResponse;
	}
	
	
	
	
	//扫码或输入云医生号时，公众号的回应
	private String thirdMemberIDDoctorCardResponse(BaseMessage baseMessage,
			String personCode, String doctorCode, String doctorName) {
		LOGGER.info("回复医生名片开始");
		// 回复医生名片内容
		NewsMessage newsMessage = new NewsMessage();
		// TODO 根据doctorInfo设置医生名片的相关信息
		// 拷贝基本属性到图文
		copyBaseMessageToSubMessage(newsMessage, baseMessage);
		newsMessage.setMsgType(WeiXBaseConstant.RESP_MESSAGE_TYPE_NEWS);
		// 设置图文消息个数
		newsMessage.setArticleCount(2);
		List<Article> lstArticle = new ArrayList<Article>();

		Article mainArticle = new Article();
		// 您好，PICC私人医生为您服务
		mainArticle.setTitle("您好，PICC私人医生为您服务");

		// 进入IM的图片
		mainArticle.setPicUrl(WeiXBaseConstant.WEIXIN_DOMAIN_URL + "/wx/res/images/doctor_attention_picc.png");
		// 拼接IM主页链接
		String imUrl = WeiXBaseConstant.WEIXIN_DOMAIN_URL
				+ "/wx/page/index/#/consult?doctorCode=" + doctorCode
				+ "&personCode=" + personCode;
		mainArticle.setUrl(imUrl);

		lstArticle.add(mainArticle);
	
		Article subArticle = new Article();
		// PICC专属私人医生----守护健康生活
		subArticle.setTitle("PICC专属私人医生----守护健康生活");
		// 了解更多主页
		subArticle.setDescription("PICC专属私人医生----守护健康生活");
		// 图片&链接
		subArticle.setPicUrl(WeiXBaseConstant.WEIXIN_DOMAIN_URL + "/wx/res/images/doctor_80_80_picc.png");
		subArticle.setUrl(WeiXBaseConstant.WEIXIN_DOMAIN_URL + "/wx/page/piccpresentation");
		lstArticle.add(subArticle);

		newsMessage.setArticles(lstArticle);

		String strResponse = MessageUtil.messageToXml(newsMessage);
		return strResponse;
	}

   
	
	
	
	
}